package com.game.connection.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;

import com.game.connection.message.Message;
import com.game.entity.Ship;
import com.game.listener.ShipListener;
import com.game.listener.dispatcher.ShipDispatcher;
import com.game.listener.event.ShipEvent;

public class ClientMultiplayer implements Runnable {

	private int port;

	private int playerId = -1;

	private String ip;

	private BufferedReader in;

	private Socket socket = null;

	private PrintWriter out = null;

	private Ship ship;
	private HashMap<Integer, Ship > ships;

	public ClientMultiplayer(String ip, int port, Ship ship, HashMap<Integer, Ship > ships) {
		this.port = port;
		this.ip = ip;
		this.ship = ship;
		this.ships = ships;
	}

	public void createConnection() {
		// Create socket connection
		try {
			socket = new Socket(ip, port);
			/* TODO: alterado */
//			socket.setSoTimeout(1000);
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));

		} catch (UnknownHostException e) {
			System.exit(1);
		} catch (IOException e) {
			System.out.println("No I/O");
			System.exit(1);
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		createConnection();

		Message msg = new Message();
		while (playerId == -1) {
			try {
				if (playerId == -1) {
					String txt = in.readLine();
					Message msgInit = new Message();
					msgInit.setTxt(txt);
					playerId = msgInit.getId();
					ship.setId(playerId);
					
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}

		try {
			ClientPlayerSender runnableSender = new ClientPlayerSender(playerId, socket.getOutputStream(), ship,ships);

			Thread threadPlayerLister = new Thread(new ClientPlayerListener(playerId, socket,ships));
			Thread threadPlayerSender = new Thread(runnableSender);
			threadPlayerSender.setName("sender-" + playerId);

			ShipDispatcher.getInstance().addShipListener(runnableSender);

			threadPlayerLister.start();
			threadPlayerSender.start();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
